package com.silence.kotlinapp.fragment

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.chad.library.adapter.base.BaseQuickAdapter
import com.silence.kotlinapp.R
import com.silence.kotlinapp.adapter.GankDefaultAdapter
import com.silence.kotlinapp.model.GankData
import com.silence.kotlinapp.mvp.controller.GankAndroidController
import com.silence.kotlinapp.mvp.presenter.Impl.GankAndroidPresenterImpl
import kotlinx.android.synthetic.main.fragment_gank_default.*
import org.jetbrains.anko.support.v4.toast

class GankAndroidFragment : BaseFragment(), GankAndroidController.View, BaseQuickAdapter.RequestLoadMoreListener {

    companion object {
        @JvmStatic
        fun newInstance(): GankAndroidFragment {
            return GankAndroidFragment()
        }
    }

    private lateinit var mPresenter: GankAndroidController.Presenter
    private lateinit var mAdapter: GankDefaultAdapter
    var page = 1
    var flag = true


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mPresenter = GankAndroidPresenterImpl(this@GankAndroidFragment)

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_gank_default, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()

        initData()
    }

    private fun initData() {
        mPresenter.loadData(page)
    }

    private fun initView() {
        mAdapter = GankDefaultAdapter(null)
        mAdapter.openLoadAnimation()
        mAdapter.setEnableLoadMore(true)
        mAdapter.setOnLoadMoreListener(this, recycler)

        recycler.layoutManager = LinearLayoutManager(context)
        recycler.adapter = mAdapter

    }

    override fun onLoadMoreRequested() {
        initData()
    }



    override fun onError(msg: String, code: Int) {
        toast(msg)
        mAdapter.loadMoreFail()
    }

    override fun onNetFinish() {
        if (mAdapter.isLoading) {
            mAdapter.loadMoreComplete()
        }

        if (!mAdapter.isLoadMoreEnable) {
            mAdapter.setEnableLoadMore(true)
        }
    }


    override fun onLoadSuccess(data: List<GankData>) {
        page++
        if (flag) {
            mAdapter.setNewData(data)
            flag = false
        } else {
            mAdapter.addData(data)
        }
    }

}
